package cn.sc.summer.gateway.config;

import cn.sc.summer.constant.util.MatchUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 类名：资源访问权限过滤处理
 *
 * @author a-xin
 * @date 2024/9/18 14:43
 */
@Slf4j
public class ResourceManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    /**
     * 这里的路径标识该资源路径不能访问
     */
    private static final String[] NEED_CHECK_URL = {
            "/sys"
    };

    /**
     * Determines if access is granted for a specific authentication and object.
     *
     * @param authentication the Authentication to check
     * @param authorizationContext         the object to check
     * @return an decision or empty Mono if no decision could be made.
     */
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {

        ServerWebExchange exchange = authorizationContext.getExchange();
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getPath().value();
        log.info("-> resource provider: {}", path);
        for (String url : NEED_CHECK_URL) {
            if (MatchUtil.anyMatchValue(path, url)) {
                return Mono.just(new AuthorizationDecision(false));
            }
        }

        return Mono.just(new AuthorizationDecision(true));
    }

}
